/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import exception.InvalidCommandException;
import exception.InvalidCommandReferenceException;
import java.util.LinkedList;
import java.util.Queue;

/**
 *
 * @author think
 */
public class PipeLineCommand implements Executable {

    private Queue<String> commands = new LinkedList<String>();
    private VMMachine machine;
//    private String output = "";
//    private int result = -1;
    private CommandResult result;
    private String command;

    public String getCmd() {
        return this.command;
    }

    public PipeLineCommand(String cmd) {
        this.command = cmd;
        String[] cmds = cmd.split("\\|");
        for (int i = 0; i < cmds.length; i++) {
            commands.add(cmds[i].trim());
        }
    }

    public void run() throws InvalidCommandReferenceException {
        try {
            String firstCmdStr = commands.poll();
            System.out.println("this first command is: " + firstCmdStr);
            Command firstCmd = new Command(firstCmdStr);
            firstCmd.run();
            if (firstCmd.getResult().getRc() > 0) {
                this.setResult(firstCmd.getResult());
//                this.output = firstCmd.getOutput();
//                this.result = firstCmd.getResult();
            } else {
                String result = firstCmd.getOutput();
                while (commands.size() > 0) {
                    String cmd = commands.poll();
                    Command currentCmd = new Command(cmd + " " + result);
                    currentCmd.run();
                    this.setResult(currentCmd.getResult());
//                    this.output = currentCmd.getOutput();
//                    this.result = currentCmd.getResult();
                    if (this.result.getRc() > 0) {
                        break;
                    }
                }
            }
//            this.result = 0;
//            this.output = "Composite command finished";
        } catch (InvalidCommandException ex) {
            this.setResult(new CommandResult(1, ex.getMessage()));
        }
    }

    public VMMachine getMachine() {
        return this.machine;
    }


    public void setResult(CommandResult result) {
        this.result = result;
    }


    public boolean isSucceed() {
        return this.result.isSucceed();
    }

    public boolean finished() {
        return this.result.getRc() >= 0;
    }

    public static void main(String[] args) {
        String text = "1234|5678";
        String parts[] = text.split("\\|");
        System.out.println(parts.length);
    }

    public CommandResult getResult() {
        return this.getResult();
    }
}
